#ifndef SERVERTCP_H
#define SERVERTCP_H

#include <QTcpServer>
#include <QTcpSocket>
#include <QDataStream>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>

// 定义常量端口号
#define DEFAULT_HOST ("127.0.0.1")
#define LOGIN_PORT (8080)
#define REGISTER_PORT (8081)
#define CONNECT_PORT (8082)

// 定义数据相关端口号
#define USERS_DATA (8888)
#define DOCTORS_DATA (8889)
#define PATIENTS_DATA (8890)
#define MEDICAL_RECORDS_DATA (8891)
#define APPOINTMENTS_DATA (8892)
#define MEDICAL_ADVICE_DATA (8893)
#define PRESCRIPTIONS_DATA (8894)
#define COMMUNICATION_DATA (8895)
#define HEALTH_ASSESSMENTS_DATA (8896)
#define DEPARTMENTS_DATA (8898)
#define APPOINTMENTS_DATA_2 (9999)

#define INSERT_DATA (8897)
#define SUCCESS (1)
#define FAILED (0)
#define FAILTED_CODE ("failed")

// ServerTcp类继承自QTcpServer
class ServerTcp : public QTcpServer {
    Q_OBJECT

public:
    explicit ServerTcp(QObject *parent = nullptr); // 无参构造函数
    ServerTcp(qint16 port, const QString &host = DEFAULT_HOST, QObject *parent = nullptr); // 带参数构造函数

    QByteArray getData() const { return data; } // 获取数据
    QString getJsonString() const { return jsonString; } // 获取JSON字符串
    QJsonArray jsonArray; // 用于存储JSON数组

public slots:
    void onNewConnection(); // 新连接的处理函数
    void sendMsg(const QString&); // 发送消息
    void onInsertData();

    // 处理返回数据的槽函数
    void onReadMsg_ReturnUsers();
    void onReadMsg_ReturnDoctors();
    void onReadMsg_ReturnPatients();
    void onReadMsg_ReturnMedicalRecords();
    void onReadMsg_ReturnAppointments();
    void onReadMsg_ReturnAppointments_2();
    void onReadMsg_ReturnMedicalAdvice();
    void onReadMsg_ReturnPrescriptions();
    void onReadMsg_ReturnCommunication();
    void onReadMsg_ReturnHealthAssessments();
    void onReadMsg_ReturnDepartments();

    // 发送数据的槽函数
    void sendUsersData();
    void sendDoctorsData();
    void sendPatientsData();
    void sendMedicalRecordsData();
    void sendAppointmentsData();
    void sendAppointmentsData_2();
    void sendMedicalAdviceData();
    void sendPrescriptionsData();
    void sendCommunicationData();
    void sendHealthAssessmentsData();
    void sendDepartmentsData();
//新加通信
    void onNewConnection_2();
    void onReadyRead();
    void onDisconnected();
signals:
    void dataReceived(const QByteArray &data); // 数据接收信号

private:
    QByteArray data; // 存储接收到的数据
    QTcpSocket *socket; // 当前连接的socket
    QString sql; // SQL查询字符串
    QString jsonString; // JSON字符串
    qint16 port; // 端口号

    QTcpServer *m_server;
    QMap<QTcpSocket*, QString> m_clients;
};

#endif // SERVERTCP_H
